package com.ruoyi.web.controller.qif;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.qif.domain.BillImageUploadDTO;
import com.ruoyi.qif.domain.QifRoom;
import com.ruoyi.qif.service.IQifRoomService;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.qif.domain.QifBill;
import com.ruoyi.qif.service.IQifBillService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.thymeleaf.util.ObjectUtils;

/**
 * 琦风公寓-每月账单Controller
 *
 * @author David
 * @date 2025-10-05
 */
@Controller
@RequestMapping("/qif/bill")
public class QifBillController extends BaseController {
    private String prefix = "qif/bill";

    @Autowired
    private IQifBillService qifBillService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IQifRoomService qifRoomService;

    @RequiresPermissions("qif:bill:view")
    @GetMapping()
    public String bill(ModelMap mmap) {
        // 1. 获取本月去重的交租日列表（调用之前实现的Service方法）
        List<Long> rentPayDateList = qifBillService.getDistinctRentPayDates();
        mmap.put("rentPayDateList", rentPayDateList); // 存入模型
        mmap.put("roomList", qifRoomService.selectQifRoomList(new QifRoom()));
        return prefix + "/bill";
    }
    /**
     * 账单列表单元格更新（本月水/本月电）
     * @param billId 账单ID
     * @param fieldName 字段名（thisMonthWater/thisMonthElectricity）
     * @param fieldValue 字段值
     */
    @PostMapping("/updateCell")
    @ResponseBody
    public AjaxResult updateBillCell(@RequestBody Map<String, Object> param) {
        try {
            // 1. 解析参数（确保参数非空）
            Long billId = Convert.toLong(param.get("billId"));
            String fieldName = Convert.toStr(param.get("fieldName"));
            BigDecimal fieldValue = Convert.toBigDecimal(param.get("fieldValue"));

            if (billId == null || StringUtils.isBlank(fieldName) || fieldValue == null) {
                return AjaxResult.error("参数不能为空");
            }

            // 2. 调用Service更新指定字段
            qifBillService.updateBillCell(billId, fieldName, fieldValue);
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }
    /**
     * 查询琦风公寓-每月账单列表
     */
    @RequiresPermissions("qif:bill:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QifBill qifBill) {
        startPage();
        List<QifBill> list = qifBillService.selectQifBillList(qifBill);
        return getDataTable(list);
    }

    /**
     * 导出琦风公寓-每月账单列表
     */
    @RequiresPermissions("qif:bill:export")
    @Log(title = "琦风公寓-每月账单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QifBill qifBill) {
        List<QifBill> list = qifBillService.selectQifBillList(qifBill);
        ExcelUtil<QifBill> util = new ExcelUtil<QifBill>(QifBill.class);
        return util.exportExcel(list, "琦风公寓-每月账单数据");
    }
    /**
     * 获取本月账单中去重的交租日列表（用于下拉框）
     */
    @GetMapping("/distinctRentPayDates")
    @ResponseBody
    public AjaxResult getDistinctRentPayDates() {
        List<Long> dates = qifBillService.getDistinctRentPayDates();
        return AjaxResult.success(dates);
    }
    @RequiresPermissions("qif:bill:add")
    @Log(title = "琦风公寓-生成本月账单", businessType = BusinessType.INSERT)
    @PostMapping("/generateCurrentMonthBills")
    @ResponseBody
    public AjaxResult generateCurrentMonthBills() {
        return toAjax(qifBillService.generateCurrentMonthBills());
    }

    @GetMapping("/get/{billId}")
    @ResponseBody
    public AjaxResult get(@PathVariable("billId") Long billId) {
        QifBill qifBill = qifBillService.selectQifBillByBillId(billId);
        return AjaxResult.success(qifBill);
    }


    /**
     * 新增保存琦风公寓-每月账单
     */
    @RequiresPermissions("qif:bill:add")
    @Log(title = "琦风公寓-每月账单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(QifBill qifBill) {
        return toAjax(qifBillService.insertQifBill(qifBill));
    }

    /**
     * 修改琦风公寓-每月账单
     */
    @RequiresPermissions("qif:bill:edit")
    @GetMapping("/edit/{billId}")
    public String edit(@PathVariable("billId") Long billId, ModelMap mmap) {
        QifBill qifBill = qifBillService.selectQifBillByBillId(billId);
        mmap.put("qifBill", qifBill);
        return prefix + "/edit";
    }

    /**
     * 修改保存琦风公寓-每月账单
     */
    @RequiresPermissions("qif:bill:edit")
    @Log(title = "琦风公寓-每月账单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QifBill qifBill) {
        return toAjax(qifBillService.updateQifBill(qifBill));
    }

    /**
     * 删除琦风公寓-每月账单
     */
    @RequiresPermissions("qif:bill:remove")
    @Log(title = "琦风公寓-每月账单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(qifBillService.deleteQifBillByBillIds(ids));
    }


    /**
     * 上传账单图片（对应前端uploadBillImage接口）
     * @param dto 图片上传参数（billId + Base64字符串）
     * @return 上传结果
     */
    @PostMapping("/uploadBillImage")
    @ResponseBody
    public AjaxResult uploadBillImage(@Validated @RequestBody BillImageUploadDTO dto) {
        try {
            // 调用Service处理图片上传逻辑
            String imageUrl = qifBillService.uploadBillImage(dto);
            // 返回成功结果（包含图片URL，可选）
            return AjaxResult.success("账单图片保存成功", imageUrl);
        } catch (ServiceException e) {
            // 业务异常（如账单不存在、Base64解码失败）
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            // 系统异常（如存储失败）
            e.printStackTrace();
            return AjaxResult.error("保存图片异常，请重试！");
        }
    }

    /**
     * 获取基础电费（配置键：qif.room.basicElectricityCharge）
     */
    @GetMapping("/getBaseElectricityFee")
    @ResponseBody
    public AjaxResult getBaseElectricityFee() {
        // 从配置表查询基础电费
        String basicElectricityCharge = configService.selectConfigByKey("qif.room.basicElectricityCharge");
        if (StringUtils.isNull(basicElectricityCharge)){
            basicElectricityCharge="0.84";
        }
        return AjaxResult.success(basicElectricityCharge);
    }
}
